package com.lzhsite.technology.designPattern.strategy.GuessDemo;

import java.util.Random;

public class SecondType implements IGuessType
{
    private Random random;
    private int preHand = 0;
    private int currentHand = 0;
    //history[上一次出招][本次出招] = 获胜的次数
    //history[0][0] = 10 上一次出石头,本次出出石头总共获胜10次
    private int[][] history =
            {
                    {1, 1, 1},
                    {1, 1, 1},
                    {1, 1, 1}
            };

    public SecondType(int seed)
    {
        this.random = new Random(seed);
    }

    //算法比较复杂，还未理解
    public Hand nextHand()
    {
        int nowRandom = random.nextInt(getTotalWin(currentHand));
        int handValue = 0;
        if (nowRandom < history[currentHand][0])
        {
            handValue = 0;
        } else if (nowRandom < history[currentHand][1] + history[currentHand][0])
        {
            handValue = 1;
        } else
        {
            handValue = 2;
        }
        preHand = currentHand;
        currentHand = handValue;
        return Hand.getHand(handValue);
    }

    public void whetherWin(boolean win)
    {
        if (win)
        {
            history[preHand][currentHand]++;
        } else
        {
            history[preHand][(currentHand + 1) % 3]++;
            history[preHand][(currentHand + 2) % 3]++;
        }
    }

    private int getTotalWin(int preHand)
    {
        int total = 0;
        for (int i = 0; i < 3; i++)
        {
            total += history[this.preHand][i];
        }
        return total;
    }
}
